package projorientado.ocr.impl;

import java.util.Iterator;
import java.util.Vector;
import projorientado.image.ImageComparator;
import projorientado.image.ImageComparatorProvider;
import projorientado.image.ImageLayerData;
import projorientado.image.ImageLayerDataProvider;
import projorientado.ocr.OCRProvider;
import projorientado.ocr.OCRecognizer;
import projorientado.spi.ServiceProvider;
import projorientado.util.CodeTokenizer;
import projorientado.util.CodeTokenizer.CodeElement;
import projorientado.util.CodeTokenizer.CodeLine;
import projorientado.util.CodeTokenizer.CodeVarDef;

public class SimpleRecognizerProvider implements ServiceProvider<OCRecognizer> {

    private static final SimpleRecognizerProvider instance = new SimpleRecognizerProvider();
    
    static {
        OCRProvider.getInstance().registerServiceProvider("simpleRecognizer", instance);
    }
    
    private SimpleRecognizerProvider() {
        
    }
    
    public static SimpleRecognizerProvider getInstance() {
        return instance;
    }
    
    public OCRecognizer getService(String s) {
        CodeTokenizer.CodeBlock root = CodeTokenizer.singleParse(s);
        
        ImageComparator imgComp = null;
        Vector<AlphabetChar> alpha = new Vector();
        
        Iterator<CodeTokenizer.CodeElement> it = root.childs.iterator();
        while(it.hasNext()) {
            CodeElement e = it.next();
            if(e instanceof CodeTokenizer.CodeTextBlock) {
                CodeTokenizer.CodeTextBlock tblock = (CodeTokenizer.CodeTextBlock)e;
                String name = tblock.name.toLowerCase();
                
                if(name.startsWith("ocr:") || name.startsWith("ocrecognizer:")) {
                    String service = tblock.name.substring(name.indexOf(':')+1);
                    imgComp = ImageComparatorProvider.getImageComparator(service,tblock.text);
                } else if(name.startsWith("alphabet") || name.startsWith("alpha")) {
                    loadAlphabet(alpha,tblock.text);
                }
            }
        }
        
        return new SimpleRecognizer(alpha,imgComp);
    }

    private void loadAlphabet(Vector<AlphabetChar> v, String text) {
        CodeTokenizer.CodeBlock root = CodeTokenizer.singleParse(text);
        Iterator<CodeTokenizer.CodeElement> it = root.childs.iterator();
        while(it.hasNext()) {
            CodeElement e = it.next();
            if(e instanceof CodeTokenizer.CodeTextBlock) {
                CodeTokenizer.CodeTextBlock tblock = (CodeTokenizer.CodeTextBlock)e;
                char c = tblock.name.charAt(0);
                AlphabetChar ac = new AlphabetChar();
                ac.setCharValue(c);
                ImageLayerData imgData = ImageLayerDataProvider.getImageLayerData(tblock.text);
                ac.setImage(imgData);
                v.add(ac);
            }
        }
    }
    
}
